package com.binarysoft.cmdhandler.operlog;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.StringTokenizer;

import com.binarysoft.service.operlog.OperLog;
import com.binarysoft.service.operlog.OperLogService;
import com.binarysoft.service.user.UserInfo;
import com.binarysoft.service.user.UserService;

import common.framework.command.handler.AbstractCommandHandler;
import common.framework.command.helper.CommandHelper;
import common.framework.command.server.Terminal;
import common.framework.dsb.annotation.DSBCmd;
import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;

@DSBCmd("operlog")
public class OperLogCmdHandler extends AbstractCommandHandler {

	@Override
	public void handle(String args, Terminal terminal) throws Exception {
		terminal.println("");
		StringTokenizer stier = new StringTokenizer(args);
		int count = stier.countTokens();
		if (count < 2) {
			showOperLogOptions(terminal);
			return;
		}
		stier.nextToken();
		String cmd = stier.nextToken();
		if ("ls".equalsIgnoreCase(cmd)) {
			if (count == 2) {
				showOperlog(terminal, "", false);
			} else if (count == 3) {
				String userID = stier.nextToken();
				shwoOperLogByUid(terminal, userID);
			}
		} else if ("del".equalsIgnoreCase(cmd)) {
			if (count == 2) {
				delOperlog(terminal, "", false);
			} else if (count == 3) {
				String userID = stier.nextToken();
				delOperLogByUid(terminal, userID);
			}
		} else {
			showOperLogOptions(terminal);
		}
		terminal.println("");
	}

	private void showOperLogOptions(Terminal terminal) throws Exception {
		terminal.println(" operlog ls                 --show a time operlog");
		terminal.println(" operlog ls    <User ID>    --show user a time operlog");
		terminal.println(" operlog del       		  --delete a time operlog");
		terminal.println(" operlog del   <User ID>    --delete user a time operlog");
		terminal.println("");
	}

	private void showOperlog(Terminal terminal, String userID, boolean isByUserID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		OperLogService operLogService = serviceFactory.lookup("DSB/OperLogService");
		boolean flag = true;
		long beginTime = 0;
		while (flag) {
			terminal.print("Please input operlog begin time('yyyy-MM-dd HH:mm:ss'):");
			String beginTimeStr = terminal.read();
			if (isDateExist(beginTimeStr)) {
				Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginTimeStr);
				beginTime = d.getTime();
				break;
			} else {
				terminal.println("Invalid input format!\n");
				continue;
			}
		}
		long endTime = 0;
		while (flag) {
			terminal.print("\nPlease input operlog end time('yyyy-MM-dd HH:mm:ss'):");
			String endTimeStr = terminal.read();
			if (isDateExist(endTimeStr)) {
				Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTimeStr);
				endTime = d.getTime();
				break;
			} else {
				terminal.println("Invalid input format!");
				continue;
			}
		}
		Collection<OperLog> result;
		if (isByUserID) {
			result = operLogService.queryOperLog(beginTime, endTime, userID);
		} else {
			result = operLogService.queryOperLog(beginTime, endTime);
		}
		if (result != null && result.size() < 1) {
			terminal.println("\n0 operlog(s) was found!");
			return;
		}
		terminal.println("");
		String[] tableHAD = { "OperLog ID", "OperLog Name", "Description", "Status", "User ID", "Oper Time" };
		String[] tableGAP = { "----------", "------------", "-----------", "------", "-------", "---------" };
		int[] format = { 20, 15, 20, 8, 20, 15 };
		terminal.println(CommandHelper.format(tableHAD, format));
		terminal.println(CommandHelper.format(tableGAP, format));
		for (OperLog operLog : result) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date dt = operLog.getOperTime();
			String sDateTime = sdf.format(dt);
			Object[] row = { operLog.getLogid(), operLog.getOperTime(), operLog.getOperdesc(), operLog.getOperstatus(), operLog.getUserId(), sDateTime };
			terminal.println(CommandHelper.format(row, format));
		}
		terminal.println("\nQuery operLog result Size : " + result.size());
	}

	private void shwoOperLogByUid(Terminal terminal, String userID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = serviceFactory.lookup("DSB/UserService");
		UserInfo upUser = userService.getUserByID(Long.parseLong(userID));
		if (upUser == null) {
			terminal.println("User ID [" + userID + "] not found.\n");
			terminal.print("Need show all user list?<Y/N>:");
			if ("Y".equalsIgnoreCase(terminal.read())) {
				terminal.println("");
				// showAllUser
			}
			return;
		}
		showOperlog(terminal, userID, true);
	}

	private void delOperlog(Terminal terminal, String userID, boolean isByUserID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		OperLogService operLogService = serviceFactory.lookup("DSB/OperLogService");
		boolean flag = true;
		long beginTime = 0;
		while (flag) {
			terminal.print("Please input operlog begin time('yyyy-MM-dd HH:mm:ss'):");
			String beginTimeStr = terminal.read();
			if (isDateExist(beginTimeStr)) {
				Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginTimeStr);
				beginTime = d.getTime();
				break;
			} else {
				terminal.println("Invalid input format!\n");
				continue;
			}
		}
		long endTime = 0;
		while (flag) {
			terminal.print("\nPlease input operlog end time('yyyy-MM-dd HH:mm:ss'):");
			String endTimeStr = terminal.read();
			if (isDateExist(endTimeStr)) {
				Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTimeStr);
				endTime = d.getTime();
				break;
			} else {
				terminal.println("Invalid input format!");
				continue;
			}
		}
		terminal.print("\nAre you sure to delete? (Y/N):");
		if ("Y".equalsIgnoreCase(terminal.read())) {
			if (isByUserID) {
				operLogService.deleteLog(beginTime, endTime, userID);
			} else {
				operLogService.deleteLog(beginTime, endTime);
			}
			terminal.println("\nDelect operLog successfully!");
		}
	}

	private void delOperLogByUid(Terminal terminal, String userID) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		UserService userService = serviceFactory.lookup("DSB/UserService");
		UserInfo upUser = userService.getUserByID(Long.parseLong(userID));
		if (upUser == null) {
			terminal.println("User ID [" + userID + "] not found.\n");
			terminal.print("Need show all user list?<Y/N>:");
			if ("Y".equalsIgnoreCase(terminal.read())) {
				// showAllUser
			}
			return;
		}
		delOperlog(terminal, userID, true);
	}

	// 判断时间输入是否正确
	private static boolean isDateExist(String dtStr) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = null;
		try {
			d = sdf.parse(dtStr);
		} catch (Exception e) {
			return false;
		}
		String s1 = sdf.format(d);
		// 转换后的日期再转换回String,如果不等,逻辑错误.如format为"yyyy-MM-dd",date为
		// "2006-02-31",转换为日期后再转换回字符串为"2006-03-03",说明格式虽然对,但日期
		// 逻辑上不对.
		return dtStr.equals(s1);
	}

}
